<?php 
/**
* 
*/
class Rest
{	
	private $_user;
	private $_article;


	//请求资源
	private $_allowReource = [
		'users',
		'articles'
	];

	private $_allowMethod = [
		'GET',
		'POST',
		'DELETE',
		'PUT'
	];

	private $_version;

	private $_statusCode = [
		200 => 'OK',
		400 => 'Bad Request',
		403 => 'Forbidden',
		404 => 'Not Found',
		405 => 'No Content',
		406 => 'Request Not Allowed',
		500 => 'server Internal Error'

	];




	public function __construct(User $user,Article $article){
		$this->_user = $user;
		$this->_article = $article;
	}


	/**
	* 启动方法
	**/
	public function run() {

		try {
			$this->setReource();
			$this->setMethod();
		} catch (Exception $e) {
			$this->_json($e->getMessage(),$e->getCode());
		}
		 
		 // print_r($date);exit();
		 
		 

	}



	/**
	* 请求资源限定
	* @param var $message 请求的资源
	**/
	private function setReource() {
		$path = $_SERVER['PATH_INFO'];
		 $params = explode('/', $path);
		 // var_dump($params);
		 $message = $params['2'];
		if (!in_array($message, $this->_allowReource)) {
			throw new Exception("请求资源不被允许", 405);
			
		}

		$this->_version = $params['1'];


		// echo $message;
		// var_dump($message == 'users');
		if ($message == 'users') {
			$this->sendUsers();
		} else {
			$this->sendArticles();
		}
		// print_r($this->_version);


	}

	/**
	* 请求方法
	**/
	private function setMethod() {
		// print_r($_SERVER);die();
		$requestMethod = $_SERVER['REQUEST_METHOD'];
		 if (!in_array($requestMethod, $this->_allowMethod)) {
		 	throw new Exception("请求方法不被允许", 406);
			
		 }
	}


	/**
	* 处理用户模块请求
	**/

	private function sendUsers(){
		
	}


	/**
	* 处理文章模块请求
	**/


	private function sendArticles() {
		
	}

	private function _json($message,$code){
		if ($code !== 200) {
			header("HTTP/1.0 406 乱码");
			// header("Content-type: text/html; charset=utf-8"); 
			header('HTTP/1.1' . ' ' . $code . ' ' . $this->_statusCode[$code]);
		}
		
		if (!empty($message)) {
			header('Content-type:application/json;charset=utf-8');
			echo json_encode(['message'=>$message,'code'=>$code]);
		}
		
	}
}
